package com.fucheng.transport;

import com.fucheng.common.RpcRequest;
import com.fucheng.common.RpcResponse;
import com.fucheng.server.ServerRegistry;
import com.fucheng.server.ServiceConfig;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

/**
 * Netty服务端业务处理器：处理客户端发来的RpcRequest请求
 */
public class SimpleServerHandler extends SimpleChannelInboundHandler<RpcRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcRequest rpcRequest) {
        RpcResponse rpcResponse = new RpcResponse();

        try{
            // 查找服务实现
//            String serviceKey = rpcRequest.getServiceName() + ":" + rpcRequest .getVersion();
            ServiceConfig<?> serviceConfig = ServerRegistry.getService(rpcRequest.getServiceName(), rpcRequest.getVersion());
            Object ref = serviceConfig.getRef();

            // 反射调用方法
            Method method = ref.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsTypes());
            Object result = method.invoke(ref, rpcRequest.getParams());

            // 构造响应
            rpcResponse.setData(result);
            rpcResponse.setMessage("success");
        }catch (Exception e) {
            rpcResponse.setMessage("error: " + e.getMessage());
            rpcResponse.setData(null);
            e.printStackTrace();
        }

        // 写回响应
//        channelHandlerContext.writeAndFlush(rpcResponse);
        // 写回响应并关闭连接
        channelHandlerContext.writeAndFlush(rpcResponse).addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace(); // 打印错误栈
        ctx.close();             // 关闭连接，避免资源泄露
    }
}
